﻿#include "mainwindow.h"

#include <QApplication>
#include <SendMessage/comchange.h>
#include <QMutex>
#include <QDir>

bool TIMEflag = true;
QString logName;

//#define LOG_FILE     qApp->applicationDirPath()+"/logger.txt"  
void outputMessage(QtMsgType type, const QMessageLogContext& context, const QString& msg)
{
	static QMutex mutex;
	mutex.lock();
	QString text;
	switch (type)
	{
	case QtDebugMsg:
		text = QString("Debug:");
		break;
	case QtWarningMsg:
		text = QString("Warning:");
		break;
	case QtCriticalMsg:
		text = QString("Critical:");
		break;
	case QtFatalMsg:
		text = QString("Fatal:");
	default:
		break;
	}
	QString context_info = QString("[%1 %2]:").arg(QString(context.function)).arg(context.line);//文件名,所在行数
	QString current_date = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
	QString message = QString("%1 %2 %3").arg(current_date).arg(text).arg(msg);//.arg(context_info).arg(msg);
	QFileInfo info("./OceanPlot.exe");
	QString absolutePath = info.absolutePath();
	QString dirName = absolutePath + "/Log";
	QDir dir(dirName);
	if (!dir.exists())
	{
		dir.mkdir(dirName);
		qDebug() << "文件夹创建成功";
	}
	if (TIMEflag)
	{
		TIMEflag = false;
		logName = QDateTime::currentDateTime().toString("yyyyMMddhhmmss") + ".log";
	}
	QString fileName = dirName + "/" + logName;
	QFile file(fileName);
	file.open(QIODevice::WriteOnly | QIODevice::Append);
	QTextStream text_stream(&file);
	text_stream << message << "\r\n";
	file.flush();
	file.close();
	mutex.unlock();
}

int main(int argc, char *argv[])
{
	// 日志
	qInstallMessageHandler(outputMessage);//安装消息处理器调用回调函数

    QApplication a(argc, argv);
#if 0
    // 不同分辨率的适配
    QApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
    QCoreApplication::setAttribute(Qt::AA_UseHighDpiPixmaps);
    qreal  cx = GetSystemMetrics(SM_CXSCREEN);
    qreal scale = cx / 1920;
    if (scale >= 0.7) {
        scale = 1;
    }
    qputenv("QT_SCALE_FACTOR", QString::number(scale).toLatin1());
#endif  
    MainWindow w;
    ComChange p;
    // 热插拔注册
    a.installNativeEventFilter(&p);
    //设置 窗口最大化
    w.showMaximized();

    return a.exec();
}
